package service

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"math/rand"
	"mts/user_srv/global"
	"mts/user_srv/internal/domain"
	"mts/user_srv/internal/repository/cache"
	"mts/user_srv/internal/service/sms"
	"strings"
	"time"
)

type CodeService interface {
	SendSMS(form domain.SendSmsForm) error
	GetCode(str string) (string, error)
}

type ExCodeService struct {
	codeCache cache.CodeCache
	sms       sms.Service
}

func NewCodeService(codeCache *cache.CodeCache, smsSvc sms.Service) sms.Service {
	return &ExCodeService{
		codeCache: *codeCache,
		sms:       smsSvc,
	}
}

func GenerateSmsCode(width int) string {
	//生成width长度的短信验证码
	numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numeric)
	rand.Seed(time.Now().UnixNano())

	var sb strings.Builder
	for i := 0; i < width; i++ {
		fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
	}
	return sb.String()
}

func (svc *ExCodeService) GetCode(str string) (string, error) {
	result, err := svc.codeCache.Get(context.Background(), fmt.Sprintf("smscode:%s", str)).Result()
	return result, err
}
func (svc *ExCodeService) SendSMS(form domain.SendSmsForm) error {
	code := GenerateSmsCode(5)
	zap.S().Infof("注册验证码:%s ", code)

	key := fmt.Sprintf("smscode:%s", form.Mobile)
	// 保存到 Redis，并设置过期时间
	err := svc.codeCache.Set(context.Background(), key, code, time.Duration(global.ServerConfig.RedisInfo.Expire)*time.Second).Err()
	return err
}
